<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\model\HousingResources;
use app\admin\model\AdminAdmins;
use app\admin\model\BusinessCircle;
use app\admin\model\ResidentialQuarters;
use app\admin\model\UserAccount;
use app\admin\model\Room;
use app\admin\model\RentalInformation;
use think\Db;

class HousingRes extends BaseAdmin
{
    /**
     * 房源列表
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $where_new = [];
        if ($_GET) {
            $where = $_GET;
            if (!empty($where['bc_name'])) {
                $bc_id_obj = BusinessCircle::where([['bc_name','like','%'.$where['bc_name'].'%']])
                    ->field('bc_id')
                    ->select();
                $bc_id_arr = array_column($bc_id_obj->toArray(),'bc_id');
                $where_new[] = ['ty_housing_resources.hr_bc_id','in',$bc_id_arr];
            }

            if (!empty($where['rq_name'])) {
               $bc_id_obj = ResidentialQuarters::where([['rq_name','like','%'.$where['rq_name'].'%']])
                   ->field('rq_id')
                   ->select();
               $rq_id_arr = array_column($bc_id_obj->toArray(),'rq_id');
               $where_new[] = ['ty_housing_resources.hr_rq_id','in',$rq_id_arr];
            }

            if (!empty($where['hr_serial_number'])) {
              $where_new[]  = ['ty_housing_resources.hr_serial_number','=',$where['hr_serial_number']];
            }

            if (!empty($where['hr_status'])) {
             $where_new[]   = ['ty_housing_resources.hr_status','=',$where['hr_status']];
            }

            if (!empty($where['hr_sales_id'])) {
             $where_new[]   = ['ty_housing_resources.hr_sales_id','=',$where['hr_sales_id']];
            }

            if (!empty($where['hr_cm_id'])) {
             $where_new[] = ['ty_housing_resources.hr_cm_id','=',$where['hr_cm_id']];
            }

            if (!empty($where['hr_owner'])) {
                $where_new[] = ['ty_housing_resources.hr_owner','like','%'.$where['hr_owner'].'%'];
            }

            if (!empty($where['hr_city'])) {
                $where_new[] = ['ty_housing_resources.hr_city','like','%'.$where['hr_city'].'%'];
            }

            $this->assign('where',$where);
        }
        //业务员列表
        $saleslist = AdminAdmins::selectAll();

        $list = HousingResources::aselect($where_new);

        $this->assign('data',$list);

        $this->assign('saleslist',$saleslist);

        if (Request()->isAjax()) {
            return json($list);
        }

        return $this->fetch();
    }

    /**
     * 业务员获取渠道
     */
    public function salesTochannel()
    {
        $param = request()->param();
        //渠道员
        $channellist    = AdminAdmins::find(['id'=>$param['hr_sales_id']])->channelMember;

        //业主
        //$ownerslist     = AdminAdmins::find(['id'=>$param['hr_sales_id']])->ownerslist;

        ajaxReturn(0,['channellist'=>$channellist]);
    }

    /**
     * 显示指定房源
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function housingRead($id)
    {

        $info = HousingResources::adetail(['hr_id'=>$id]);

        //业务员列表
        $saleslist = AdminAdmins::selectAll();
        $channellist = AdminAdmins::find($info['hr_sales_id']);

        if ($channellist) {
            //渠道员列表
            $channellist = AdminAdmins::find($info['hr_sales_id'])->channelMember;
            $this->assign('channellist',$channellist);
        }

        //商圈列表
        $businesscircle = BusinessCircle::zselect();

        //小区列表
        $quarters = ResidentialQuarters::zselect();

        $this->assign('saleslist',$saleslist);
        $this->assign('hr_id',$id);
        $this->assign('businesscircle',$businesscircle);
        $this->assign('quarters',$quarters);
        return view('housing_read', ['info'=>$info]);
    }


    /**
     * 房源出租详情
     * @param $house_id
     * @return \think\response\View
     */
    public function housingRental($house_id)
    {
        $this->assign("house_id",$house_id);
        return view('housing_rental');
    }

    /**
     * 房源出租信息添加
     */
    public function housingRentalAdd()
    {
        $param = request()->param();

        $obj = RentalInformation::create($param['data']);

        if ($obj->ri_id) {
            ajaxReturn(0);
        }
        ajaxReturn(3);

    }

    /**
     * 商圈获取小区
     */
    public function  circleToQuarters()
    {
        $param = request()->param();

        //渠道员
        $circleToQuarters    = BusinessCircle::find(['rq_bc_id'=>$param['hr_bc_id']])->circleToQuarters;

        ajaxReturn(0,$circleToQuarters);
    }

    /**
     * 房源编辑
     */
    public function housingEdit()
    {
        $param_str = urldecode(request()->param('data'));

        $param_arr_z = explode("&",$param_str);

        $param = [];

        foreach ($param_arr_z as $k=>$v) {
            $arr = explode("=",$v);
            $param[$arr[0]] = $arr[1];
        }
        $res = HousingResources::zsave($param);

        if ($res) {
            return ajaxReturn(0);
        }

        return ajaxReturn(1);
    }

    /**
     * 添加房源.
     *
     * @return \think\Response
     */
    public function HousingCreate()
    {
        if (request()->param()) {

            $param_str = urldecode(request()->param('data'));

            $param_arr_z = explode("&",$param_str);

            $param = [];

            foreach ($param_arr_z as $k=>$v) {
                $arr = explode("=",$v);
                $param[$arr[0]] = $arr[1] ?? '';
            }
            $param['hr_serial_number'] = 'TY'.date("YmdHis",time()).mt_rand(10,99);

            //查询添加业主表
            $au = UserAccount::zselect(['hr_owner_phone'=>$param['hr_owner_phone']]);
            Db::startTrans();
            try {
                if (!$au) {
                    UserAccount::zcreate([
                        'ua_phone'=>$param['hr_owner_phone'],
                        'ua_name'=>$param['hr_owner'],
                        'ua_type'=>3,
                    ]);
                }
                HousingResources::zadd($param);
                Db::commit();
                ajaxReturn(0);
            } catch (\Exception $e) {
                Db::rollback();
            }
            ajaxReturn(1);
        }

        //业务员列表
        $saleslist = AdminAdmins::selectAll();

        //商圈列表
        $businesscircle = BusinessCircle::zselect();


        $this->assign("saleslist",$saleslist);
        $this->assign("businesscircle",$businesscircle);

        return view('housing_add');
    }

    /**
     * 房间列表
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function roomList(Request $request)
    {
        $where = [['room_num','<>',0]];
        if (Request()->isPost()) {
            $param = request()->param();

            if (!empty($param['house_id'])) {
                $where[] = ['house_id','=',$param['house_id']];
            }

            if (!empty($param['r_id'])) {
                $where[] = ['r_id','=',$param['r_id']];
            }
            $this->assign('where',$param);
        }

        $res = Room::zselect($where);
        $this->assign('roomlist',$res);
        return  view('room_list');
    }

    /**
     * 添加房间
     */
    public function roomAdd()
    {
        $param = request()->param();

        if (Request()->isPost()) {
            //查询是否有房间
            $res = Room::zselect(['house_id'=>$param['data']['house_id']]);
            if ($res->isEmpty()) {
                unset($param['data']['filename']);
                $new_param[0]                   = $param['data'];
                $new_param[0]['room_num']       = 0;
                $new_param[0]['update_time']    = time();
                $new_param[0]['create_time']    = time();
                $new_param[1]                   = $param['data'];
                $new_param[1]['update_time']    = time();
                $new_param[1]['create_time']    = time();
            } else {
                $check_room = Room::where([
                    'room_num'=>$param['data']['room_num'],
                    'house_id'=>$param['data']['house_id']
                ])->find();

                if ($check_room) {
                    ajaxReturn(2);
                }
                $new_param[0]                   = $param['data'];
                $new_param[0]['update_time']    = time();
                $new_param[0]['create_time']    = time();
            }

            $res = Room::zcreate($new_param);
            if ($res->isEmpty()) {
                ajaxReturn(1);
            }
            ajaxReturn(0);
        }

        $res = Room::zselect([['house_id','=',$param['house_id']],['room_num','<>',0]]);

        if ($res->isEmpty()) {
            $this->assign("room_num",1);
        } else {
            $room_num = $res[0]->room_num+1;

            if ($room_num==4) {
                $room_num =5;
            }

            $this->assign("room_num",$room_num);
        }
        $this->assign("roomlist",$res->items());
        $this->assign("house_id",$param['house_id']);
        return view("room_add");
    }

    /**
     * 房间编辑.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function roomEdit()
    {
        $param = request()->param();
        if (Request()->isPost()) {

            $row = Room::zupdate($param['data']);

            if (!$row) {
                ajaxReturn(2);
            }
            ajaxReturn(0);
        }

        $res = Room::zselect(['r_id'=>$param['r_id']]);

        if ($res[0]->photo_url) {
            $photo_url = explode(",",$res[0]->photo_url);
            $this->assign("photo_url",$photo_url);
        }
        $this->assign("room",$res[0]);
        $this->assign("r_id",$param['r_id']);
        return view("room_edit");
    }

    /**
     * 删除房间
     */
    public function roomDel()
    {
        $r_id = Request()->param('r_id');

        $bool = Room::destroy($r_id);

        if ($bool) {
            ajaxReturn(0);
        }
        ajaxReturn(3);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }


    /**
     * 单文件上传
     */
    public function upload(){
        $file = request()->file('filename');

        if(!$file){
            ajaxReturn(20001);
        }

        if (empty(request()->param('type'))) {
            $type = '';
        } else {
            $type = "/".request()->param('type');
        }
        $info = $file->validate(config('fileupload.contract'))->move(config('fileupload.dirpath').$type);

        if ($info) {

            $imgurl = str_replace("\\","/",config('fileupload.dirpath').$type."/".$info->getSaveName());

            ajaxReturn(0,['imgUrl'=>$imgurl]);
        } else {
            ajaxReturn(10013,$file->getError());
        }
    }

    /**
     * 电量修改
     */
    public function  statisticsEdit()
    {
        $param = request()->param();
        $HousingResources = new HousingResources();
        $res = $HousingResources->save($param,['hr_id'=>$param['hr_id']]);
        if (!$res) {
            ajaxReturn(3);
        }
        ajaxReturn(0);
    }

}
